<?php

namespace app\api1\controller;

use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\View;
use think\facade\Db;
use think\response\Json;
/**
 * 机器人
 *
 * api-Robot
 *
 * @Apidoc\Title("机器人")
 * @Apidoc\Group("api1")
 */
class Robot extends Auth
{
    /**
     * list
     * @Apidoc\Title("列表")
     */
    public function list(): \think\response\Json
    {
        $res = \app\common\model\Robot::where('member_id', $this->request->uid)->order('id' ,'asc')->select();
        $res = $res->toArray();
        foreach ($res as $i => $item) {
            $res[$i] = $item;
            $expiration_time = $item['expiration_time'];
            $state = 0;
            if($expiration_time==0){
                $state = -1;
            }else{
                if($expiration_time<time()){
                    $state = 1;
                }
            }

            $product_name = \app\common\model\RobotProducts::where('id', $item['robot_products_id'])->value('name');

            $res[$i]['product_name'] = $product_name;
            $res[$i]['state'] = $state;
            $res[$i]['count_conversation'] = \app\common\model\RobotConversation::where('robot_id', $item['id'])->count();
            $res[$i]['count_messages'] = \app\common\model\RobotConversationMessage::where('robot_id', $item['id'])->count();

            $res[$i]['word_count'] = number_format($item['word_count']);
            $res[$i]['percent_conversation'] = ($item['daily_conversation_limit'] ? intval( $item['number_of_conversations_today']/ $item['daily_conversation_limit']  * 100): 0) . '%';
            $res[$i]['percent_word'] = ($item['word_limit'] ? intval( $item['word_count']/ $item['word_limit']  * 100): 0) . '%';;
            $res[$i]['expiration_time_str'] = date('Y-m-d H:i:s', $item['expiration_time']);
        }
        return success('ok', $res);
    }


    /**
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Apidoc\Title("详情")
     * @Apidoc\Method("post")
     * @Apidoc\Param("robot_id", type="int", default="1", desc="机器人id")
     */
    public function getStatus()
    {

        $robot_id = input('robot_id', 0, 'intval');
        $robot = \app\common\model\Robot::find($robot_id);
        $where = [];
        if($robot_id){
            $where[] = ['robot_id', '=', $robot_id];
        }
        $start_time = input('start_time');
        $end_time = input('end_time');
        if($start_time && $end_time){
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time) + 86400 -1;
            $where[] = ['create_time', 'between', [$start_time, $end_time]];
        }
        $chat_count = \app\common\model\RobotConversation::where($where)->count();
        $message_count = \app\common\model\RobotConversationMessage::where($where)->count();
        $like_count = \app\common\model\RobotConversationMessage::where($where)
            ->where('is_positive_reviews', 1)->count();
        $unlike_count = \app\common\model\RobotConversationMessage::where($where)
            ->where('is_positive_reviews', -1)->count();
        $event_count = \app\common\model\RobotConversationMessage::where($where)
            ->where('is_event_submission', 1)->count();
        $events = \app\common\model\RobotConversationMessage::where($where)
            ->where('is_event_submission', 1)->select()
            ->each(function($item){
                $item['answer_time_str'] = date('Y-m-d H:i:s', $item['answer_time']);
            });
        $word_count = $robot['word_count'];
        $word_percent =  number_format(($word_count / $robot['word_limit']) * 100, 2);
        $file_count = \app\common\model\RobotFiles::where('robot_id', $robot_id)
            ->where('is_url', 0)->count();
        $url_count = \app\common\model\RobotFiles::where('robot_id', $robot_id)
            ->where('is_url', 1)->count();
        return success('', [
            'chat_count' => $chat_count,
            'message_count' => $message_count,
            'like_count' => $like_count,
            'unlike_count' => $unlike_count,
            'event_count' => $event_count,
            'word_count' => number_format($word_count, 0, '.', ','),
            'word_percent' => $word_percent,
            'file_count' => $file_count,
            'url_count' => $url_count,
            'events' => $events,
        ]);

    }



    /**
     * delete
     * @Apidoc\Method("post")
     * @return Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Apidoc\Title("删除")
     */
    public function delete()
    {
        $id = input('id');
        $robot = \app\common\model\Robot::find($id);
        if($robot['member_id'] != $this->request->uid) {
            return error('非法请求');
        }
        $find = \app\common\model\RobotFiles::where('robot_id', $id)->find();
        if($find) {
            return error('该机器人下有文件，不能删除');
        }
        \app\common\model\Robot::destroy($id);
        $conversion_ids = \app\common\model\RobotConversation::where('robot_id', $id)->column('id');
        \app\common\model\RobotConversation::destroy($conversion_ids);
        $conversion_message_ids = \app\common\model\RobotConversationMessage::where('robot_conversation_id','in',  $conversion_ids)->column('id');
        \app\common\model\RobotConversationMessage::destroy($conversion_message_ids);
        return success();
    }


    /**
     * update
     * @Apidoc\Title("修改")
     * @Apidoc\Method("post")
     */
    public function update()
    {
        $data = request()->post(['id',
            'name',
            'brief_introduction',
            'welcome_message',
            'title',
            'subtitle',
            'consultation_icon',
            'opening_remarks',
            'advanced_style_settings',
            'preset_questioning_options',
            'is_gpt_answer',
            'unable_to_answer_content',
            ]);
        validate([
            'name|名称' => 'require',
            'id|id' => 'require',
        ])->check($data);
        $robot = \app\common\model\Robot::find($data['id']);
        if($robot['member_id'] != $this->request->uid) {
            return error('非法请求');
        }
        \app\common\model\Robot::update($data);
        return success($data);
    }

    /**
     * @return Json|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @Apidoc\Title("详情")
     */
    public function getById()
    {
        $id = input('id');
        $robot = \app\common\model\Robot::where('member_id', $this->request->uid)->find($id);
        if(!$robot){
            return error('非法请求');
        }
        return success('', $robot);
    }

    /**
     * upload
     * @Apidoc\Title("上传文件")
     */
    public function upload()
    {
        $robot_id = input('robot_id',0,'intval');
        $file = request()->file();
        try{
            $rules = [
                'file' => [
                    'fileExt' =>  'jpg,png,jpeg',
                    'fileSize' =>   2 * 1024 * 1024
                ]
            ];
            validate($rules)->check($file);
        }catch (ValidateException $e) {
            return error($e->getMessage(),'', '', 500);
        }
        $file = $file['file'];
        $save_path = \think\facade\Filesystem::disk('public')->putFile('memberUpload/' . $robot_id  , $file);
        $save_path = '/storage/' . $save_path;
        return success('上传成功', ['url'=>$save_path]);
    }


    /**
     * @Apidoc\Title("获取安装地址")
     */
    public function getInstallUrl()
    {
        $base_url = config('front_end.chat_window_url');
        $robot_id = input('robot_id',0,'intval');
        $robot = \app\common\model\Robot::where('member_id', $this->request->uid)
            ->where('id', $robot_id)
            ->find();
        if(!$robot){
            return error('非法请求');
        }
        $self_url = rtrim(config('wechat.base_url'),'/');
        $js_url = <<<EOF
        <script src="{$self_url}/chat.js" chat-bot-code="{$robot['code']}" chat-bot-url="$base_url" chat-bot-width="400px" chat-bot-height="600px"></script>
EOF;
        $iframe_url = <<<EOF
                <iframe src="{$base_url}/#/alRobot/chat/chat?code={$robot['code']}" ></iframe>
EOF;
        return success('', [
            'js_url' => $js_url,
            'iframe_url' => $iframe_url,
            'is_enable' => $robot['is_enable_js'],
        ]);

    }


    /**
     * @Apidoc\Title("设置能否js安装")
     */
    public function setJsStatus()
    {
        $robot_id = input('robot_id',0,'intval');
        $status = input('status',0,'intval');
        $robot = \app\common\model\Robot::where('member_id', $this->request->uid)
            ->where('id', $robot_id)
            ->update(['is_enable_js'=>$status]);
        return success();
    }

    /**
     * @Apidoc\Title("获取分享地址")
     */
    public function getShareUrl()
    {
        $base_url = config('front_end.chat_window_url');
        $robot_id = input('robot_id',0,'intval');
        $robot = \app\common\model\Robot::where('member_id', $this->request->uid)
            ->where('id', $robot_id)
            ->find();
        $share_url = $base_url . '/#/alRobot/chat/share?share_code=' . $robot['code'];
        $share_password = $robot['share_password'];
        if(!$share_password) {
            $share_password = rand(1000, 9999);
            \app\common\model\Robot::where('id', $robot_id)->update(['share_password'=>$share_password]);
        }
        return success('', [
            'share_url' => $share_url,
            'share_password' => $share_password,
            'is_share' => $robot['is_enable_sharing'],
        ]);
    }

    /**
     * @Apidoc\Title("设置能否分享")
     */
    public function setShareStatus()
    {
        $robot_id = input('robot_id',0,'intval');
        $status = input('status',0,'intval');
        $robot = \app\common\model\Robot::where('member_id', $this->request->uid)
            ->where('id', $robot_id)
            ->update(['is_enable_sharing'=>$status]);
        return success();
    }

    /**
     * @Apidoc\Title("设置分享密码")
     */
    public function setSharePassword()
    {
        $robot_id = input('robot_id',0,'intval');
        $password = input('password',0,'trim');
        $robot = \app\common\model\Robot::where('member_id', $this->request->uid)
            ->where('id', $robot_id)
            ->update(['share_password'=>$password]);
        return success();
    }


}
